﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;
using System.Windows.Controls.Primitives;
using System.Text.RegularExpressions;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using Coding4Fun.Phone.Controls;
using System.Text;

namespace YiDingCanWp7
{
    public class Distance {
        public int value { get; set; }
        public string name { get; set; }
    }
    public class OrderCat {
        public string value { get; set; }
        public string name { get; set; }
    }
    public partial class ShopList : PhoneApplicationPage
    {
        ObservableCollection<ShopDTO> shopCollection=new ObservableCollection<ShopDTO>(); 
        bool Isfirst = true;
        string type = string.Empty;
        Popup popup = new Popup() { IsOpen = false };
        public bool IsLoaded = false;
        bool IsLoading = false;
        SearchSettings set = new SearchSettings();
        string url = BaseConfig.BaseUrl + "/Shop/ShopsForMobile?lat={0}&lng={1}&distance={2}&pageIndex={3}&pageSize={4}&title={5}&shopcatids={6}&order={7}";
        string MyShareUrl = BaseConfig.MyShareUrl;
        int pageindex = 1;
        int pagesize =20;
        bool haveMore = true;
        int total = 0;
        private bool firstload = true;
        private bool HaveMore
        {
            get
            {
                if (firstload||total>(pageindex-1)*pagesize)
                {
                    return true;
                }
                return false;
            }
        }
        public ShopList()
        {
            InitializeComponent();
            performanceProgressBar.IsIndeterminate = false;

        }
        void GetShops(string order="")
        {
            try
            {
                if (IsLoading) return;
                if (!HaveMore)
                {
                    ToastPrompt toast = new ToastPrompt(); //实例化 
                    if (total==0)
                    {
                        toast.Title = "没有符合要求的商家"; //设置标题 
                      //  toast.Message = "没有符合要求的商家"; //设置正文消息 
                    }
                    else
                    {
                        toast.Title = "已经是最后一页"; //设置标题 
                     //   toast.Message = "已经是最后一页"; //设置正文消息 
                        
                    }

                    toast.FontSize = 35; //设置文本大小(可选) 
                    toast.TextOrientation = System.Windows.Controls.Orientation.Vertical; //设置呈现为纵向 
                    // toast.ImageSource = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));    //设置 标题前的图片(可选) 
                    toast.Background = new SolidColorBrush(Colors.LightGray); //背景色(可选) 
                    toast.Foreground = new SolidColorBrush(Colors.Red); //前景色(可选)
                    toast.Completed += toast_Completed; //Toast显示完毕后触发事件(可选) 
                    toast.Show();
                    return;
                }
                if (firstload)
                {
                    firstload = false;
                }
                performanceProgressBar.IsIndeterminate = true;
                if (order.Equals(""))
                {
                    order = "Avg|desc";
                }
                string shopcats = string.Empty;
                if (set.BoolDinner)
                {
                    shopcats = "1";
                }
                if (set.BoolFlower)
                {
                    if (shopcats == string.Empty)
                    {
                        shopcats = "3";
                    }
                    else
                    {
                        shopcats = shopcats + ",3";
                    }
                }
                if (set.BoolSuperMarket)
                {
                    if (shopcats == string.Empty)
                    {
                        shopcats = "4";
                    }
                    else
                    {
                        shopcats = shopcats + ",4";
                    }
                }
                if (set.BoolDrug)
                {
                    if (shopcats == string.Empty)
                    {
                        shopcats = "5";
                    }
                    else
                    {
                        shopcats = shopcats + ",5";
                    }
                }
                string title = string.Empty;
                if (this.NavigationContext.QueryString.ContainsKey("title"))
                {
                    title = this.NavigationContext.QueryString["title"];
                }
                Uri uri = new Uri(string.Format(url, Utils.GetLocationProperty()[0], Utils.GetLocationProperty()[1],new SearchSettings().Distance.Value, pageindex, pagesize, title, shopcats, order));
                WebClient webClient = new WebClient();
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers["Accept-type"] = "application/json";
                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
                webClient.DownloadStringAsync(uri);
                IsLoading = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                performanceProgressBar.IsIndeterminate = false;
            }
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }
        private void Search_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SearchSetting.xaml", UriKind.RelativeOrAbsolute));
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AddShop.xaml", UriKind.RelativeOrAbsolute));
        }
        private void ShopList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ShopsList.SelectedIndex != -1)
            {
                NavigationService.Navigate(new Uri("/ShopDetailPivot.xaml?shopid=" + ((ShopDTO)ShopsList.SelectedItem).ShopId, UriKind.RelativeOrAbsolute));
            }
        }
        void webClient_DownloadStringCompletedMyShare(object sender, DownloadStringCompletedEventArgs e) {
            try
            {

                performanceProgressBar.IsIndeterminate = true;
                Shops shops = JsonConvert.DeserializeObject<Shops>(e.Result);
                ShopsList.ItemsSource = shops.items;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {

                performanceProgressBar.IsIndeterminate = false;
            }
        }
        void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                var shops = JsonConvert.DeserializeObject<Shops>(e.Result);
                if(shopCollection==null)
                {
                    shopCollection = new ObservableCollection<ShopDTO>();
                    ShopsList.ItemsSource = shopCollection;
                }
                foreach (ShopDTO shop in shops.items)
                {
                    shopCollection.Add(shop);
                }
                pageindex++;
                total = shops.total;
                PageTitle.Text = "附近(" + total.ToString() + ")";
                if ((pageindex - 1) * pagesize > total)
                {
                    haveMore = false;
                }

                IsLoaded = true;
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally {

                performanceProgressBar.IsIndeterminate = false;
                IsLoading = false;
            }
        }
        private void Refresh_Click(object sender, EventArgs e)
        {
            pageindex = 1;
            haveMore = true;
            switch (type)
            {
                case "share":
                    GetMyShareShops();
                    break;
                default:
                GetShops();
                    break;
            }
        }


        public static T FindChildOfType<T>(DependencyObject root) where T : class
        {
            var queue = new Queue<DependencyObject>();
            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                DependencyObject current = queue.Dequeue();
                for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
                {
                    var child = VisualTreeHelper.GetChild(current, i);
                    var typedChild = child as T;
                    if (typedChild != null)
                    {
                        return typedChild;
                    }
                    queue.Enqueue(child);
                }
            }
            return null;
        }
        
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            List<ScrollBar> scrollBarList = GetVisualChildCollection<ScrollBar>(ShopsList);
            foreach (ScrollBar scrollBar in scrollBarList)
            {
                if (scrollBar.Orientation == System.Windows.Controls.Orientation.Horizontal)
                {

                }
                else
                {
                    scrollBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(verticalScrollBar_ValueChanged);
                }
            }
            if (!IsLoaded)
            {
                type = NavigationContext.QueryString["type"];
                switch (type)
                {
                    case "latest":
                        PageTitle.Text = "最近使用";
                        break;
                    case "local":
                        List<Distance> distances = new List<Distance>();
                        distances.Add(new Distance() { value = 500, name = "500米内" });
                        distances.Add(new Distance() { value = 1000, name = "1千米内" });
                        distances.Add(new Distance() { value = 2000, name = "2千米内" });
                        distances.Add(new Distance() { value = 5000, name = "5千米内 " });
                        distances.Add(new Distance() { value = 10000, name = "10千米内 " });
                        distances.Add(new Distance() { value = 20000, name = "20千米内 " });
                        listBox_distance.ItemsSource = distances;
                        listBox_distance.SelectionChanged += new SelectionChangedEventHandler(listBox_distance_SelectionChanged);
                        if (set.BoolDistance500)
                        {
                            listBox_distance.SelectedIndex = 0;
                            GetShops();
                        }
                        if (set.BoolDistance1000)
                        {
                            listBox_distance.SelectedIndex = 1;
                        }
                        if (set.BoolDistance2000)
                        {

                            listBox_distance.SelectedIndex = 2;
                        }
                        if (set.BoolDistance5000)
                        {
                            listBox_distance.SelectedIndex = 3;
                        }
                        if (set.BoolDistance10000)
                        {
                            listBox_distance.SelectedIndex = 4;
                        }
                        if (set.BoolDistance20000)
                        {
                            listBox_distance.SelectedIndex = 5;
                        }
                        List<OrderCat> orderCats = new List<OrderCat>();
                        orderCats.Add(new OrderCat() { value = "avg|desc", name = "评价高↓" });
                        orderCats.Add(new OrderCat() { value = "modified|desc", name = "最新↓" });
                        orderCats.Add(new OrderCat() { value = "taste|desc", name = "口味好↓" });
                        orderCats.Add(new OrderCat() { value = "speed|desc", name = "速度快↓" });
                        orderCats.Add(new OrderCat() { value = "qos|desc", name = "服务好↓" });
                        listBox_order.ItemsSource = orderCats;
                        listBox_order.SelectionChanged += new SelectionChangedEventHandler(listBox_order_SelectionChanged);
                        // listBox_order.SelectedIndex = 0;
                        //GetShops();
                        PageTitle.Text = "附近餐馆";
                        break;
                    case "favorite":
                        PageTitle.Text = "收藏餐馆";
                        listBox_distance.Visibility = Visibility.Collapsed;
                        listBox_order.Visibility = Visibility.Collapsed;
                        break;
                    case "share":
                        PageTitle.Text = "我的分享";
                        listBox_distance.Visibility = Visibility.Collapsed;
                        listBox_order.Visibility = Visibility.Collapsed;
                        GetMyShareShops();
                        break;
                }
            }
            ShopsList.ItemsSource = shopCollection;
 
        }
        void GetMyShareShops() {

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers["Accept-type"] = "application/json";
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompletedMyShare);
            string encode = string.Format(MyShareUrl, HttpUtility.UrlEncode(PhoneUtils.GetDeviceUniqueId()));
            webClient.DownloadStringAsync(new Uri(encode), UriKind.Absolute);    
        }
        private void MenuItemPhone_Click(object sender, RoutedEventArgs e)
        {
            ShopDTO contextMenuDataItem = (ShopDTO)(sender as MenuItem).Tag;
            //MessageBox.Show(contextMenuDataItem.Phone);
            appbar_MakeACall_Click(contextMenuDataItem);

        }
        private void appbar_MakeACall_Click(ShopDTO shop)
        {
            Regex regex = new Regex(@"((\d{11})|((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})))", RegexOptions.IgnorePatternWhitespace);
            if (string.IsNullOrEmpty(shop.Phone))
            {
                MessageBox.Show("号码不存在!");
                return;
            }
            MatchCollection mc = regex.Matches(shop.Phone);
            if (mc.Count > 1)
            {
                popup.Height = 300;
                popup.Width = 400;
                popup.VerticalOffset = 100;
                PopupControl control = new PopupControl();
                foreach (Match item in mc)
                {
                    Button ctrl = new Button();
                    ctrl.Content = item.Value;
                    ctrl.Tag = shop;
                    ctrl.Click += new RoutedEventHandler(ctrl_Click);
                    control.LayoutRoot.Children.Add(ctrl);
                }
                popup.Child = control;
                popup.IsOpen = true;
            }
            else if (mc.Count > 0)
            {
                LatestShopsSettings.Add(shop);
                PhoneCallTask p = new PhoneCallTask();
                p.PhoneNumber = mc[0].Value;
                p.Show();
            }
        }

        void ctrl_Click(object sender, RoutedEventArgs e)
        {
            ShopDTO contextMenuDataItem = (ShopDTO)(sender as Button).Tag;
            LatestShopsSettings.Add(contextMenuDataItem);
            PhoneCallTask p = new PhoneCallTask();
            p.PhoneNumber = ((Button)sender).Content.ToString();
            p.Show();
            popup.IsOpen = false;
        }
        void toast_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
            //add some code here
        }

        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            ShopDTO contextMenuDataItem = (ShopDTO)(sender as MenuItem).Tag;
            FavoriteShops.AddFavorate(contextMenuDataItem);
           
            ToastPrompt toast = new ToastPrompt(); //实例化 

            toast.Title = "收藏成功"; //设置标题 
            toast.Message = "收藏成功"; //设置正文消息 
            toast.FontSize = 50; //设置文本大小(可选) 
            toast.TextOrientation = System.Windows.Controls.Orientation.Vertical; //设置呈现为纵向 
            toast.ImageSource = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));    //设置 标题前的图片(可选) 
            toast.Background = new SolidColorBrush(Colors.LightGray); //背景色(可选) 
            toast.Foreground = new SolidColorBrush(Colors.Red); //前景色(可选)


            toast.Completed += toast_Completed; //Toast显示完毕后触发事件(可选) 
            toast.Show();
        }

        private void listBox_distance_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listBox_distance.SelectedIndex != -1)
            {
                haveMore = true;
                firstload = true;
                new SearchSettings().Distance.Value= ((Distance)listBox_distance.SelectedItem).value;
                shopCollection = null;
                pageindex = 1;
                GetShops("");
            }
        }

        private void listBox_order_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ////如果是第一次加载则激活
            if (listBox_order.SelectedIndex!=-1)
            {
                firstload = true;
                haveMore = true;
                shopCollection = null;
                pageindex = 1;
                GetShops(((OrderCat)listBox_order.SelectedItem).value);
            }
         // if (Isfirst) Isfirst = false;
        }

        private void ShopsList_MouseMove(object sender, MouseEventArgs e)
        {

        }

        private void verticalScrollBar_ValueChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                ScrollBar scrollBar = (ScrollBar)sender;
                object valueObj = scrollBar.GetValue(ScrollBar.ValueProperty);
                object maxObj = scrollBar.GetValue(ScrollBar.MaximumProperty);
                if (valueObj != null && maxObj != null)
                {
                    double value = (double)valueObj;
                    double max = (double)maxObj - 1.0;
                    if (value >= max)
                    {
                        GetShops();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           
        }
        public static List<T> GetVisualChildCollection<T>(object parent) where T : UIElement
        {
            List<T> visualCollection = new List<T>();
            GetVisualChildCollection(parent as DependencyObject, visualCollection);
            return visualCollection;
        }

        private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : UIElement
        {
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (child is T)
                {
                    visualCollection.Add(child as T);
                }
                else if (child != null)
                {
                    GetVisualChildCollection(child, visualCollection);
                }
            }
        }

        
    }
}